//
//  AddPuechaseViewController.m
//  YYPHSpeedJump
//
//  Created by speedjump on 16/1/30.
//  Copyright © 2016年 sujiang. All rights reserved.
//

#import "AddPuechaseViewController.h"
#import "GoodNameTableViewCell.h"
#import "ChineseInclude.h"
#import "PinYinForObjc.h"
#import "ReasonTableViewCell.h"

@interface AddPuechaseViewController ()<UITextViewDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong)NSMutableArray *myArray;
@property (nonatomic, copy) NSString *testPath;
@end

@implementation AddPuechaseViewController
- (NSMutableArray *)goodDatalist
{
    if (!_goodDatalist) {
    
        _goodDatalist = [NSMutableArray array];
    }
    return _goodDatalist;
}
- (NSMutableArray *)reasonlist
{
    if (!_reasonlist) {
        _reasonlist = [NSMutableArray array];
        
    }
    return _reasonlist;
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title =@"添加心愿";
    self.rightBtn= [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnAction:)];
    self.navigationItem.rightBarButtonItem = self.rightBtn;
    self.readonView.layer.borderWidth = 1;
    self.readonView.layer.cornerRadius = 5;
    self.readonView.layer.borderColor = kColors(198, 203, 208, 0.9).CGColor;
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(reasonBtnAction:)];
    tapG.numberOfTapsRequired = 1;
    [self.readonView addGestureRecognizer:tapG];
    self.putdownImage.image = [UIImage imageNamed:@"xiala"];
    [self createFile];
    [self addSubviews];
    
     [self requestData];
}

- (void)setModel:(GoodNameModel *)model
{
    self.goodModel =model;
}
- (void)requestData
{
    NSString *url = [NSString stringWithFormat:@"%@/app.do?cmd=wish_commodity_list",kBaseUrl];
   [NetworkHandle getInfoWithUrl:url dictionary:nil success:^(NSDictionary *dictionary) {
       NSArray *array = dictionary[@"data"];
       NSLog(@"%@",array[0]);
       [self writeFileArr:array];
       [self reloadPlist];
   }];
    NSString *reasonUrl = [NSString stringWithFormat:@"%@/accounts/wish_reason",kNewBaseUrl];
    [NetworkHandle getInfoWithUrl:reasonUrl dictionary:nil success:^(NSDictionary *dictionary) {
        NSArray *array =dictionary[@"data"];
        [self.reasonlist addObjectsFromArray:array];
        [self.reasonTableView reloadData];
        
    }];
    
}

- (void)reloadPlist
{
    
    NSArray *array = [NSArray arrayWithContentsOfFile:self.testPath];

    for (NSDictionary *dic in array) {
        GoodNameModel *model = [[GoodNameModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.goodDatalist addObject:model];
        
    }
        self.arr2 = [NSMutableArray arrayWithArray:self.goodDatalist];
        [self.tableView reloadData];
}


- (void)addSubviews
{

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.goodName.frame.origin.x, 37, self.goodName.width, 0)];
    self.tableView.delegate =self;
    self.tableView.dataSource =self;
    self.tableView.layer.borderWidth = 1;
    self.tableView.separatorStyle =NO;
    [self.view addSubview:self.tableView];
    self.goodName.delegate = self;
    self.goodName.placeholder=@"选择商品";
     [self.goodName addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    self.reasonTableView = [[UITableView alloc]initWithFrame:CGRectMake(self.readonView.frame.origin.x, 30, self.readonView.width, 0)];
    self.reasonTableView.delegate =self;
    self.reasonTableView.dataSource =self;
    self.reasonTableView.layer.borderWidth = 1;
    self.reasonTableView.separatorStyle =NO;
    [self.view addSubview:self.reasonTableView];
    
    self.reason.delegate = self;
    self.reason.layer.borderWidth = 1;
    self.reason.layer.cornerRadius = 5;
    [self.reason.layer setBorderColor:kColors(197, 204, 207, 1).CGColor];
    self.reason.placeholder=@"理由需在6~200个字之间";
   
}
//创建路径
-(NSString *)dirDoc{
    //[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
  //  NSLog(@"app_home_doc: %@",documentsDirectory);
    return documentsDirectory;
}
-(void)createFile{
    NSString *documentsPath =[self dirDoc];
   self.testPath = [documentsPath stringByAppendingPathComponent:@"test.plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL res=[fileManager createFileAtPath:self.testPath contents:nil attributes:nil];
    if (res) {
        NSLog(@"文件创建成功: %@" ,self.testPath);
    }else
        NSLog(@"文件创建失败");
}
-(void)writeFileArr:(NSArray *)array{

    BOOL res = [array writeToFile:self.testPath atomically:YES];
    
    if (res) {
        NSLog(@"文件写入成功");
    }else
        NSLog(@"文件写入失败");
}
-(void)textFieldChanged:(id)text{
    [self.arr2 removeAllObjects];
    UITextField * te = (UITextField *)text;
    NSString *goodname = [NSString string];
    self.NewArr = [[NSMutableArray alloc] init];
    NSString *SearchText = te.text;
    //NSLog(@"%@",SearchText);
    if (SearchText.length == 0) {
        [self.arr2 addObjectsFromArray:self.goodDatalist];
        [self.tableView reloadData];
        return;
    }
    if (SearchText.length > 0 && ![ChineseInclude isIncludeChineseInString:SearchText]){//搜索栏的文字是否包含中文
        if (self.goodDatalist!=nil)
        {
            for (GoodNameModel *model in self.goodDatalist){
                
                goodname = model.wish_commodity_name;
                //判断是否包含中文
                if ([ChineseInclude isIncludeChineseInString:goodname]){//字典里面的城市名是否包含中文
                    
                    //把中文转换为拼音  进行搜索
                    NSString *goodPinYinStr = [PinYinForObjc chineseConvertToPinYin:goodname];
                    // NSLiteralSearch 区分大小写(完全比较)
                    // NSCaseInsensitiveSearch 不区分大小写
                    // NSNumericSearch 只比较字符串的个数，而不比较字符串的字面值
                    NSRange goodResult = [goodPinYinStr rangeOfString:SearchText options:NSCaseInsensitiveSearch];//要将中文转化为拼音才能搜索?
                    //返回的NSRange(范围)1应该代表有一个相同,相同的概念(bei,就有一个bei在cityPinYinStr中)
                    if (goodResult.length > 0) {
                        [self.NewArr addObject:model];
                    }
                    
                    
                }else{//字典里面的城市名不包含中文
                    NSRange titleResult=[goodname rangeOfString:SearchText options:NSCaseInsensitiveSearch];
                    if (titleResult.length>0) {
                        [self.NewArr addObject:model];
                    }
                }
                
            }
        }else{
           // NSLog(@"为空");
        }
        
        // 中文搜索
    }else if (SearchText.length > 0 && [ChineseInclude isIncludeChineseInString:SearchText]){
        [self.NewArr removeAllObjects];
        for (GoodNameModel *model in self.goodDatalist){
            goodname = model.wish_commodity_name;
            NSRange titleResult = [goodname rangeOfString:SearchText options:NSCaseInsensitiveSearch];
            
            if (titleResult.length>0) {
                [self.NewArr addObject:model];
            }
        }
    }
    [self.arr2 removeAllObjects];
    [self.arr2 addObjectsFromArray:self.NewArr];
    [self.tableView reloadData];

}

#pragma mark--------textfield Delegate-------
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.tableView.frame =CGRectMake(self.goodName.frame.origin.x,37,self.goodName.width, kScreenHeight-103-260);
    
}

#pragma mark ------------点击事件--------------
- (void)reasonBtnAction:(UIButton *)btn
{
    
    self.reasonTableView.frame =CGRectMake(self.readonView.frame.origin.x, 129, self.readonView.width, kScreenHeight-260-131);
    self.putdownImage.transform = CGAffineTransformMakeRotation(M_PI);
}

- (void)rightBtnAction:(UIBarButtonItem *)btn
{
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"logined"]) {
        [Tools showAlert:@"您还未登录,请到个人登录!"];
        return;
    }
    NSString *text = [self.reason.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (text.length< 1) {
        [Tools showAlert:@"你输入的内容不能为空"];
    }else{
        NSString *urlStr = [NSString stringWithFormat:@"%@/user.do?cmd=make_new_wish", kBaseUrl];
        
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"wish_commodity_id"]!=nil) {
            
            NSDictionary *dict = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"wish_commodity_id":[[NSUserDefaults standardUserDefaults]objectForKey:@"wish_commodity_id"], @"wish_reason":self.reason.text};
            [NetworkHandle getUpDataWithUrl:urlStr class:NSClassFromString(@"PurchaseModel") dictionary:dict firstKey:@"data" secondKey:@"list" success:^(NSArray *array) {
                self.myArray = [NSMutableArray arrayWithArray:array];
                
        [self.navigationController popViewControllerAnimated:YES];
            }];
        }
        
    }
    
}
#pragma mark---------------tableviewDelegate-----------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return self.arr2.count;

    }
    return self.reasonlist.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView){
    GoodNameTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"GoodNameTableViewCell" owner:nil options:nil]lastObject];
    }
    cell.model = self.arr2[indexPath.row];
    return cell;
    }else{
    
    ReasonTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"reasonCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"ReasonTableViewCell" owner:nil options:nil]lastObject];
    }
    cell.reasonLable.text = self.reasonlist[indexPath.row];
    return cell;
     }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 24;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
    self.tableView.frame= CGRectMake(79, 37, self.goodName.width, 0);
    GoodNameTableViewCell *cell =[self.tableView cellForRowAtIndexPath:indexPath];
    self.goodName.text = cell.goodnameLabel.text;
    self.goodPrice.text = [NSString stringWithFormat:@"￥%@",cell.price.text];
    [[NSUserDefaults standardUserDefaults]setObject:cell.lable.text forKey:@"wish_commodity_id"];
    }
    if (tableView == self.reasonTableView) {
        self.reasonTableView.frame = CGRectMake(self.readonView.frame.origin.x, 30, self.readonView.width, 0);
        ReasonTableViewCell *cell = [self.reasonTableView cellForRowAtIndexPath:indexPath];
        self.reason.text = cell.reasonLable.text;
        self.putdownImage.transform = CGAffineTransformMakeRotation(0);
        self.reasonLabel.text = cell.reasonLable.text;

    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.reasonTableView.frame = CGRectMake(self.readonView.frame.origin.x, 30, self.readonView.width, 0);
    self.putdownImage.transform = CGAffineTransformMakeRotation(0);
     self.tableView.frame= CGRectMake(79, 37, self.goodName.width, 0);
    [self.goodName resignFirstResponder];
    [self.reason resignFirstResponder];
}
#pragma mark------------textViewDelegate----------------
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    UITextRange *selectedRange = [textView markedTextRange];
    
    //获取高亮部分
    
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //获取高亮部分内容
    
    //NSString * selectedtext = [textView textInRange:selectedRange];
    
    
    
    //如果有高亮且当前字数开始位置小于最大限制时允许输入
    
    if (selectedRange && pos) {
        
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        
        
        
        if (offsetRange.location < 200) {
            
            return YES;
            
        }
        
        else
            
        {
            return NO;
            
        }
        
    }
    
    
    
    
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    
    
    NSInteger caninputlen = 200 - comcatstr.length;
    
    
    
    if (caninputlen >= 0)
        
    {
        
        return YES;
        
    }
    
    else
        
    {
        
        NSInteger len = text.length + caninputlen;
        
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        
        NSRange rg = {0,MAX(len,0)};
        
        
        
        if (rg.length > 0)
            
        {
            
            NSString *s = [text substringWithRange:rg];
            
            
            
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            
            //既然是超出部分截取了，哪一定是最大限制了。
            
            // self.reasonText.text = [NSString stringWithFormat:@"%d/%ld",0,(long)40];
            
        }
        
        return NO;
        
    }
    
    
}
- (void)textViewDidChange:(UITextView *)textView

{
    
    UITextRange *selectedRange = [textView markedTextRange];
    
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    
    
    //如果在变化中是高亮部分在变，就不要计算字符了
    
    if (selectedRange && pos) {
        
        return;
        
    }
    
    
    
    NSString  *nsTextContent = textView.text;
    
    NSInteger existTextNum = nsTextContent.length;
    
    
    if (existTextNum > 200)
        
    {
        //截取到最大位置的字符
        
        NSString *s = [nsTextContent substringToIndex:200];
        
        
        [textView setText:s];
        
    }
    //self.reasonText.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,40- existTextNum),40];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
